<template>
  <div class="login">
    <el-form :model="userinfo" :rules="rules" ref="loginInfo" label-width="100px" class="loginInfo">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userinfo.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="userinfo.password" show-password clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { userLogin } from "../request/api";
import {mapActions} from 'vuex'
export default {
  data() {
    return {
      //输入项
      userinfo: {
        username: "",
        password: ""
      },
      //验证规则
      rules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 2, max: 15, message: "长度在 2 到 15 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 16, message: "长度在 6 到 16个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods:{
    ...mapActions(['changeUser']),
    //登录事件
   login() {
      this.$refs.loginInfo.validate(val=>{
          if(val){
               userLogin(this.userinfo)
               .then(res=>{
                 if(res.code==200){
                   this.$message.success(res.msg);
                   //把登录结果保存到本地存储中
                   this.changeUser(res.list),
                   //验证成功跳转到index界面
                   this.$router.push('/index')
                 }else{
                   this.$message.error(res.msg)
                 }
               })
               
          }else{
              console.log('验证失败');
          }
      })
    },
  }
};
</script>
<style scoped>
.login {
  width: 100%;
  height: 100vh;
  background: #ccc;
}
.loginInfo {
  width: 400px;
  height: 300px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin: -150px 0 0 -250px;
}
</style>